import { createRouter, createWebHistory } from "vue-router";
import {
  isLoggedIn,
  isAdmin,
  isMerchant,
  isUser,
  isRider,
  isTokenExpired,
  clearAuth,
  getToken,
  getUserInfo,
  getUserRole,
  debugTokenStatus,
  saveDebugLog,
} from "@/utils/auth";
import { ElMessage } from "element-plus";
import customerRoutes from "./customer"; // 导入顾客端路由
import riderRoutes from "./rider"; // 导入骑手端路由

const routes = [
  {
    path: "/",
    name: "RoleSelect",
    component: () => import("@/views/RoleSelectView.vue"),
    meta: { requiresAuth: false, redirectIfLoggedIn: true },
  },
  {
    path: "/admin/login",
    name: "AdminLogin",
    component: () => import("@/views/admin/LoginView.vue"),
    meta: { requiresAuth: false, redirectIfLoggedIn: true, role: "admin" },
  },
  {
    path: "/admin/dashboard",
    name: "AdminDashboard",
    component: () => import("@/views/admin/DashboardView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/users",
    name: "AdminUsers",
    component: () => import("@/views/admin/UsersView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/merchants",
    name: "AdminMerchants",
    component: () => import("@/views/admin/MerchantsView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/products",
    name: "AdminProducts",
    component: () => import("@/views/admin/ProductsView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/orders",
    name: "AdminOrders",
    component: () => import("@/views/admin/OrdersView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/reviews",
    name: "AdminReviews",
    component: () => import("@/views/admin/ReviewsView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/riders",
    name: "AdminRiders",
    component: () => import("@/views/admin/RidersView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/statistics",
    name: "AdminStatistics",
    component: () => import("@/views/admin/StatisticsView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/admin/profile",
    name: "AdminProfile",
    component: () => import("@/views/admin/ProfileView.vue"),
    meta: { requiresAuth: true, role: "admin" },
  },
  {
    path: "/merchant/login",
    name: "MerchantLogin",
    component: () => import("@/views/merchant/LoginView.vue"),
    meta: { requiresAuth: false, redirectIfLoggedIn: true, role: "merchant" },
  },
  {
    path: "/merchant/register",
    name: "MerchantRegister",
    component: () => import("@/views/merchant/RegisterView.vue"),
    meta: { requiresAuth: false },
  },
  {
    path: "/merchant/dashboard",
    name: "MerchantDashboard",
    component: () => import("@/views/merchant/DashboardView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/profile",
    name: "MerchantProfile",
    component: () => import("@/views/merchant/ProfileView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/store",
    name: "MerchantStore",
    component: () => import("@/views/merchant/StoreView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/orders",
    name: "MerchantOrders",
    component: () => import("@/views/merchant/OrdersView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/promotions",
    name: "MerchantPromotions",
    component: () => import("@/views/merchant/PromotionsView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/products",
    name: "MerchantProducts",
    component: () => import("@/views/merchant/ProductsView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/categories",
    name: "MerchantCategories",
    component: () => import("@/views/merchant/CategoriesView.vue"),
    meta: { requiresAuth: false, role: "merchant" },
  },
  {
    path: "/merchant/statistics",
    name: "MerchantStatistics",
    component: () => import("@/views/merchant/StatisticsView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/reviews",
    name: "MerchantReviews",
    component: () => import("@/views/merchant/ReviewsView.vue"),
    meta: { requiresAuth: true, role: "merchant" },
  },
  {
    path: "/merchant/debug",
    name: "MerchantDebug",
    component: () => import("@/views/merchant/DebugView.vue"),
    meta: { requiresAuth: false }, // 不需要认证，方便调试
  },
  // 404页面
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/NotFoundView.vue"),
    meta: { requiresAuth: false },
  },
];

// 合并顾客路由和骑手路由
const allRoutes = [...routes, ...customerRoutes, ...riderRoutes];

const router = createRouter({
  history: createWebHistory(),
  routes: allRoutes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const routeInfo = `路由跳转: 从 ${from.path} 到 ${to.path}`;
  console.log(
    `%c${routeInfo}`,
    "background: #222; color: #bada55; font-size: 12px; padding: 3px;"
  );
  saveDebugLog("ROUTE", routeInfo);

  // 检查页面是否需要认证
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);
  console.log(`%c是否需要认证: ${requiresAuth}`, "color: #2196F3");
  saveDebugLog("AUTH_CHECK", `是否需要认证: ${requiresAuth}`);

  // 检查是否已登录
  const loggedIn = isLoggedIn();
  console.log(`%c是否已登录: ${loggedIn}`, "color: #4CAF50");
  saveDebugLog("LOGIN_CHECK", `是否已登录: ${loggedIn}`);

  // 如果用户已登录，但尝试访问登录页面或身份选择页面，则重定向到对应的仪表盘页面
  const redirectIfLoggedIn = to.matched.some(
    (record) => record.meta.redirectIfLoggedIn
  );

  saveDebugLog(
    "REDIRECT_CHECK",
    `是否需要重定向已登录用户: ${redirectIfLoggedIn}`
  );

  // 如果用户已登录，且目标页面是登录页面或身份选择页面，则重定向到对应的仪表盘页面
  if (loggedIn && redirectIfLoggedIn) {
    console.log(
      "%c用户已登录，尝试访问登录页面或身份选择页面，将重定向到仪表盘",
      "color: #E91E63"
    );
    saveDebugLog(
      "REDIRECT",
      "用户已登录，尝试访问登录页面或身份选择页面，将重定向到仪表盘"
    );

    // 检查token是否过期
    if (isTokenExpired()) {
      console.log(
        "%cToken已过期，清除认证信息并提示用户",
        "background: #f44336; color: white; padding: 2px;"
      );
      saveDebugLog("TOKEN_EXPIRED", "Token已过期，清除认证信息并提示用户");
      clearAuth();
      ElMessage.error("登录已过期，请重新登录");
      if (to.path.startsWith("/admin")) {
        next("/admin/login");
      } else if (to.path.startsWith("/merchant")) {
        next("/merchant/login");
      } else if (to.path.startsWith("/customer")) {
        next("/customer/login");
      } else {
        next("/");
      }
      return;
    }

    // 根据用户角色重定向到对应的仪表盘
    if (isAdmin()) {
      console.log(
        "%c管理员用户访问登录/身份选择页，重定向到管理员仪表盘",
        "color: #9C27B0"
      );
      next("/admin/dashboard");
      return;
    } else if (isMerchant()) {
      console.log(
        "%c商家用户访问登录/身份选择页，重定向到商家仪表盘",
        "color: #9C27B0"
      );
      next("/merchant/dashboard");
      return;
    } else if (isUser()) {
      console.log(
        "%c顾客用户访问登录/身份选择页，重定向到顾客首页",
        "color: #9C27B0"
      );
      next("/customer");
      return;
    }
  }

  // 如果页面不需要认证，直接放行
  if (!requiresAuth) {
    console.log("%c页面不需要认证，直接放行", "color: #4CAF50");
    next();
    return;
  }

  // 如果页面需要认证但用户未登录，重定向到登录页
  if (requiresAuth && !loggedIn) {
    console.log(
      "%c用户未登录，但尝试访问需要认证的页面，重定向到登录页",
      "background: #f44336; color: white; padding: 2px;"
    );
    ElMessage.error("请先登录");
    if (to.path.startsWith("/admin")) {
      next("/admin/login");
    } else if (to.path.startsWith("/merchant")) {
      next("/merchant/login");
    } else if (to.path.startsWith("/customer")) {
      next("/customer/login");
    } else {
      next("/");
    }
    return;
  }

  // 如果用户已登录且页面需要认证，检查token是否过期
  if (loggedIn && requiresAuth) {
    const tokenExpired = isTokenExpired();
    console.log(
      `%cToken是否过期: ${tokenExpired}`,
      "color: #FF9800; font-weight: bold;"
    );
    saveDebugLog("TOKEN_CHECK", `Token是否过期: ${tokenExpired}`);

    if (tokenExpired) {
      console.log(
        "%cToken已过期，清除认证信息并提示用户",
        "background: #f44336; color: white; padding: 2px;"
      );
      console.log("当前token:", getToken());
      saveDebugLog("TOKEN_EXPIRED", "Token已过期，清除认证信息并提示用户");

      clearAuth();
      ElMessage.error("登录已过期，请重新登录");
      if (to.path.startsWith("/admin")) {
        next("/admin/login");
      } else if (to.path.startsWith("/merchant")) {
        next("/merchant/login");
      } else {
        next("/");
      }
      return;
    }
  }

  // 检查角色权限
  const requiredRole = to.matched.find((record) => record.meta.role)?.meta.role;
  console.log(
    `%c需要的角色权限: ${requiredRole}, 用户角色: ${getUserRole()}`,
    "color: #9C27B0; font-weight: bold;"
  );

  if (requiredRole === "admin" && !isAdmin()) {
    console.log(
      "%c用户不是管理员，但尝试访问管理员页面",
      "background: #f44336; color: white; padding: 2px;"
    );
    ElMessage.error("您没有管理员权限");
    next("/");
    return;
  }

  if (requiredRole === "merchant" && !isMerchant()) {
    console.log(
      "%c用户不是商家，但尝试访问商家页面",
      "background: #f44336; color: white; padding: 2px;"
    );
    ElMessage.error("您没有商家权限");
    next("/");
    return;
  }

  if (requiredRole === "user" && !isUser()) {
    console.log(
      "%c用户不是顾客，但尝试访问顾客页面",
      "background: #f44336; color: white; padding: 2px;"
    );
    ElMessage.error("您没有顾客权限");
    next("/");
    return;
  }

  if (requiredRole === "rider" && !isRider()) {
    console.log(
      "%c用户不是骑手，但尝试访问骑手页面",
      "background: #f44336; color: white; padding: 2px;"
    );
    ElMessage.error("您没有骑手权限");
    next("/");
    return;
  }

  // 通过所有检查，放行
  console.log(
    "%c用户通过所有检查，放行",
    "background: #4CAF50; color: white; padding: 2px;"
  );
  next();
});

export default router;
